package asher.dotatbg.http.responser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import org.apache.log4j.Logger;

import asher.dotatbg.constants.Constants;
import asher.dotatbg.constants.HttpHeaderConstants;
import asher.dotatbg.logfactory.LogFactory;


/**
 * 静态资源库
 * 在需要的时候对其做缓存和内存等的优化
 * 要最有效率地使用静态资源
 * @author AsherYuan
 *
 */
public class StaticRepository {
	
	private static Logger logger = LogFactory.getRootLogger();
	
	private OutputStream output;
	
	public StaticRepository(OutputStream output) {
		this.output = output;
	}
	
	public void sendStaticResource(String uri) {
		byte[] bytes = new byte[Constants.STATICREPOSITORY_BUFFER_SIZE];
		FileInputStream fis = null;
		try {
			File file = new File(Constants.WEB_ROOT, uri);
			if(file.exists()) {
				String header = "HTTP/1.1 200 OK\r\n" +
						  "Content-Type: text/html\r\n" + 
						  "\r\n";
				output.write(header.getBytes());
				
				fis = new FileInputStream(file);
				int ch = fis.read(bytes, 0, Constants.STATICREPOSITORY_BUFFER_SIZE);
				while(ch != -1) {
					output.write(bytes, 0, ch);
					ch = fis.read(bytes, 0, Constants.STATICREPOSITORY_BUFFER_SIZE);
				}
			} else {
				logger.info("文件未找到" + "........." + new Date().toString());
				String fileNotFound = HttpHeaderConstants.FILENOTFOUND;
				output.write(fileNotFound.getBytes());
				File errorFile = new File(Constants.WEB_ROOT, File.separator + "GlobleErrorHtml" + File.separator + "fileNotFound.html");
				fis = new FileInputStream(errorFile);
				int ch = fis.read(bytes, 0, Constants.STATICREPOSITORY_BUFFER_SIZE);
				while(ch != -1) {
					output.write(bytes, 0, ch);
					ch = fis.read(bytes, 0, Constants.STATICREPOSITORY_BUFFER_SIZE);
				}
			}
		} catch(Exception e) {
			logger.info("文件未找到" + "........." + new Date().toString());
			String fileNotFound = HttpHeaderConstants.FILENOTFOUND;
			try {
				output.write(fileNotFound.getBytes());
				File errorFile = new File(Constants.WEB_ROOT, File.separator + "GlobleErrorHtml" + File.separator + "fileNotFound.html");
				fis = new FileInputStream(errorFile);
				int ch = fis.read(bytes, 0, Constants.STATICREPOSITORY_BUFFER_SIZE);
				while(ch != -1) {
					output.write(bytes, 0, ch);
					ch = fis.read(bytes, 0, Constants.STATICREPOSITORY_BUFFER_SIZE);
				}
			} catch (IOException e1) {
				logger.info("输出流出错" + "........." + new Date().toString());
			}
		} finally {
			if(fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					logger.info("StaticRepository: " + "文件关闭流出错" + "........." + new Date().toString());
				}
			}
		}
	}
}
